package com.ja.openchat.ui.chat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.ui.found.UserTagsActivity;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.user.MobileContactInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.ja.openchat.databinding.ActivityContactBinding;
import com.ja.openchat.ui.contact.CircleUserAdapter;
import com.ja.openchat.ui.contact.MobileContactListAdapter;
import com.zy.openchat.util.ContactUtils;
import com.ja.openchat.viewmodels.MobileContactActivityViewModel;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.SideIndexBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class MobileContactHomeActivity extends BaseActivity<ActivityContactBinding, MobileContactActivityViewModel> {
    private int chooseType = 0;

    private boolean isMobile() {
        return chooseType == 0;
    }

    private ArrayList<UserInfo> mChooseUserInfos;
    private CircleUserAdapter circleUserAdapter;
    public MobileContactListAdapter contactListAdapter;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_contact;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MobileContactActivityViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MobileContactActivityViewModel.class);
    }


    public static Intent getActivityForResult(Context context) {
        return getActivityForResult(context, 1, null);
    }

    public static Intent getActivityForResult(Context context, int chooseType, ArrayList<UserInfo> userInfos) {
        Intent intent = new Intent(context, MobileContactHomeActivity.class);
        if (userInfos != null) {
            intent.putExtra("choose", userInfos);
        }
        intent.putExtra("chooseType", chooseType);
        return intent;
    }

    @Override
    public void initView() {
        super.initView();
        viewModel.setContext(this);
        if (getIntent() != null) {
            chooseType = getIntent().getIntExtra("chooseType", 0);
        }
        if (getIntent() != null && getIntent().getSerializableExtra("choose") != null) {
            ArrayList<UserInfo> chatInfos = (ArrayList<UserInfo>) getIntent().getSerializableExtra("choose");
            mChooseUserInfos = chatInfos;
        }

        binding.toolbar.tvBarTitle.setText(isMobile() ?getString(R.string.contacts_friends) : getString(R.string.home_contacts));
        ImageView backView = findViewById(R.id.iv_bar_back);
        backView.setImageResource(R.mipmap.contact_shut_down);
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        contactListAdapter = new MobileContactListAdapter(sectionList);
        contactListAdapter.setChooseType(chooseType);
        binding.recyclerView.setAdapter(contactListAdapter);

        requestContacts();

        //同步联系人
        TelegramManager.getTelegramManager().syncMyContacts();

        contactListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Section section = sectionList.get(position);
                    Object obj = section.getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        if (chooseType == 2 || chooseType == -2 || chooseType == 3) {
                            section.setChecked(!section.isChecked());
                            if (section.isChecked()) {
                                mChooseUserInfos.add(0, user);
                            } else {
                                if (!mChooseUserInfos.remove(user)) {
                                    if (mChooseUserInfos != null && mChooseUserInfos.size() > 0) {
                                        for (UserInfo userInfo : mChooseUserInfos) {
                                            if (userInfo.id == user.id) {
                                                mChooseUserInfos.remove(userInfo);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            circleUserAdapter.notifyDataSetChanged();
                            contactListAdapter.notifyItemChanged(position);
                            return;
                        }
                        if (isMobile()) {
                            //跳转个人资料详情
//                            ContactDetailActivity.start(MobileContactHomeActivity.this, user);
                            ContactDetailSingleActivity.start(MobileContactHomeActivity.this, user);
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("user", user);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        }
                    }
                }
            }
        });

        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });

        if (chooseType == 2 || chooseType == -2 || chooseType == 3) {
            if (mChooseUserInfos == null) {
                mChooseUserInfos = new ArrayList<>();
            }
            circleUserAdapter = new CircleUserAdapter(mChooseUserInfos);
            binding.userRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            binding.userRecyclerView.setAdapter(circleUserAdapter);
            binding.userRecyclerView.setVisibility(View.VISIBLE);
            binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
            binding.toolbar.tvOkRight.setText(getString(R.string.ok_text));
            binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (chooseType == 2 || chooseType == -2) {
                        saveTag();
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("users", mChooseUserInfos);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                }
            });
        }

    }

    private final int REQUEST_TAG_CODE = 121;

    private void saveTag() {
        new XPopup.Builder(this).autoDismiss(true).asConfirm(getString(R.string.dialog_title_tip)
                ,getString(R.string.save_as_label_next_use), getString(R.string.neglect_text), getString(R.string.save_as_label), new OnConfirmListener() {
            @Override
            public void onConfirm() {
                UserTagsActivity.createTag(MobileContactHomeActivity.this,REQUEST_TAG_CODE,mChooseUserInfos,chooseType==2?0:1);
            }
        }, new OnCancelListener() {
            @Override
            public void onCancel() {
                Intent intent = new Intent();
                intent.putExtra("users", mChooseUserInfos);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        }, false).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAG_CODE) {
            if (data != null && data.getParcelableExtra("usertag") != null) {
                setResult(Activity.RESULT_OK, data);
            }
            finish();
        }
    }

    public void doSearch(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            resetList(totalList);
            return;
        } else {
//            TelegramManager.getTelegramManager().searchChatsList(getApplication(), keyword, new TgResultBlock<List<Long>>() {
//                @Override
//                public void onResult(Map<String, Object> request, JsonObject response, List<Long> chatIds) {
//
//                }
//
//                @Override
//                public void onTimeout(Map<String, Object> request) {
//
//                }
//            });
        }
        localList.clear();
        if (totalList != null && totalList.size() > 0) {
            for (UserInfo userInfo : totalList) {
                if (!TextUtils.isEmpty(userInfo.displayName()) && userInfo.displayName().contains(keyword)) {
                    localList.add(userInfo);
                } else if (!TextUtils.isEmpty(userInfo.realDisplayName) && userInfo.realDisplayName.contains(keyword)) {
                    localList.add(userInfo);
                }
            }
        }
        resetList(localList);
    }

    private List<Section> sectionList = new ArrayList<>();

    private List<UserInfo> localList = new ArrayList<>();
    private List<UserInfo> totalList = new ArrayList<>();

    private List<UserInfo> tempList;

    public void requestContacts() {
        tempList = TelegramManager.getTelegramManager().getTgData().getMyContacts();
        if (tempList != null && tempList.size() > 0) {
            List<UserInfo> userInfos = new ArrayList<>();
            List<MobileContactInfo> contactInfos = ContactUtils.getIntance().getHasUserIdContactInfos();
            List<Long> userIds = new ArrayList<>();
            if (isMobile()) {
                if (contactInfos != null && contactInfos.size() > 0) {
                    for (MobileContactInfo contactInfo : contactInfos) {
                        for (UserInfo userInfo : tempList) {
                            if (contactInfo.user_id == userInfo.id) {
                                userIds.add(userInfo.id);
                                userInfos.add(userInfo);
                                break;
                            }
                        }
                    }
                }
                tempList = userInfos;
            } else {
                for (UserInfo userInfo : tempList) {
                    userIds.add(userInfo.id);
                }
            }

            TelegramManager.getTelegramManager().requestOrgContactInfos(this, userIds, new TgResultBlock<List<OrgUserInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<OrgUserInfo> obj) {
                    if (obj != null && obj.size() >= tempList.size()) {
                        for (OrgUserInfo orgUserInfo : obj) {
                            for (UserInfo userInfo : tempList) {
                                if (userInfo.id == orgUserInfo.uId) {
                                    userInfo.realDisplayName = orgUserInfo.displayName();
                                    break;
                                }
                            }
                        }
//                        for(int i = 0;i<tempList.size();i++){
//                            UserInfo userInfo = tempList.get(i);
//                            OrgUserInfo orgUserInfo = obj.get(i);
//
//                            if(i<obj.size()){
//                                userInfo.realDisplayName = obj.get(i).displayName();
//                            }
//                        }
                    }
                    reloadContacts(tempList);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    reloadContacts(tempList);
                }
            });
        } else {
            reloadContacts(tempList);
        }
    }

    private void reloadContacts(List<UserInfo> list) {
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        totalList.clear();
        totalList.addAll(list);
        resetList(list);
    }

    private void resetList(List<UserInfo> list) {
        if (list == null) {
            return;
        }
        sectionList.clear();
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }

        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    boolean isChecked = false;
                    if (mChooseUserInfos != null && mChooseUserInfos.size() > 0) {
                        for (UserInfo userInfo : mChooseUserInfos) {
                            if (userInfo.id == user.id) {
                                isChecked = true;
                                break;
                            }
                        }
                    }
                    sectionList.add(new Section(false, user, isChecked));
                }
            }
        }
        //刷新页面
        contactListAdapter.notifyDataSetChanged();
    }


}
